import { RouteRecordName, RouteRecordRaw } from 'vue-router'
import router, { errorRoutes } from './router'
import store from './store'
import { getStorage } from './utils/auth'

const routeWhiteNames: RouteRecordName[] = ['login']
const hasPermission = process.env.VUE_APP_OPEN_PERMISSION

router.beforeEach(async (to, from, next) => {
  if (hasPermission === 'false') {
    const asyncRoutes = await store.dispatch('filterRoutes', {})
    if (asyncRoutes && asyncRoutes[0]) {
      asyncRoutes.forEach((item: RouteRecordRaw) => {
        router.addRoute(item)
      })
    }
    errorRoutes.forEach((item: RouteRecordRaw) => {
      router.addRoute(item)
    })
    next()
    return
  }

  if (getStorage('token')) {
    if (store.getters.userInfo.id) {
      if (to.name === 'login') {
        next({ name: 'home_overview' })
      } else {
        next()
      }
    } else {
      try {
        const userInfo = await store.dispatch('getUserInfo')
        const asyncRoutes = await store.dispatch('filterRoutes', userInfo)
        if (asyncRoutes && asyncRoutes[0]) {
          asyncRoutes.forEach((item: RouteRecordRaw) => {
            router.addRoute(item)
          })
        }
        errorRoutes.forEach((item: RouteRecordRaw) => {
          router.addRoute(item)
        })

        next({ ...to })
      } catch (error) {
        console.error('获取用户信息：', '-------', error)
        // store.dispatch('logout')
      }
    }
  } else {
    if (routeWhiteNames.includes(to.name || '')) {
      next()
    } else {
      next({ name: 'login' })
    }
  }
})

let title = '后台管理系统'

router.afterEach(to => {
  if (to.meta?.title) {
    title = to.meta.title as string
  } else {
    title = '后台管理系统'
  }

  document.getElementsByTagName('title')[0].innerHTML = title
})
